import DefaultImage from '@/asset/default-image.png';
import ErrorComp from '@/components/common/error-comp';
import LeftToRightView from '@/components/common/motion/left-to-right-view';
import OrderStatus from '@/components/common/order-status';
import QueryImage from '@/components/common/query-image';
import HandleOrderButton from '@/components/shop/handle-order-button';
import { cn } from '@/lib/utils';
import { getOrderById } from '@/service/query/order';
import { getProductsByIds } from '@/service/query/product';
import dayjs from 'dayjs';
import Link from 'next/link';
import { z } from 'zod';

export const metadata = {
  title: '订单详情',
};

const paramSchema = z.object({
  id: z.coerce.number().int().positive(),
});

const rateArray = [0, 1, 2, 3, 4];

export default async function Page({
  params,
}: { params: Promise<{ id: string }> }) {
  const paramsRes = paramSchema.safeParse(await params);
  if (!paramsRes.success)
    return <ErrorComp message="参数错误" backPath="/shop/order" />;

  const { result: orderData, error } = await getOrderById(paramsRes.data.id);
  if (error)
    return <ErrorComp message={error.message} backPath="/shop/order" />;

  const { result: productsData, error: productsError } = await getProductsByIds(
    orderData.products.map((p) => p.id),
  );

  return (
    <LeftToRightView>
      <div className="p-5 rounded-lg bg-background min-h-[90vh] shadow-lg space-y-8">
        <div className="flex justify-between px-5 pt-5">
          <Link href="/shop/order" className="flex items-center group text-sm">
            <span className="i-ri-arrow-left-s-line group-hover:-translate-x-1 transition-all duration-300" />
            返回订单列表
          </Link>
          <OrderStatus order={orderData} />
        </div>
        {['unaccepted', 'pending', 'delivering'].includes(orderData.status) && (
          <div className="flex justify-end mr-5">
            <HandleOrderButton
              orderId={orderData.id}
              status={orderData.status}
            />
          </div>
        )}
        <div className="space-y-5">
          <div className="font-bold text-lg">商品列表</div>
          {productsError ? (
            <div className="text-center py-10">{productsError.message}</div>
          ) : (
            orderData.products.map(({ id, count }) => {
              const product = productsData.find((p) => p.id === id);
              if (!product) return null;
              return (
                <div key={id} className="flex justify-between items-center ">
                  <div className="flex items-end gap-4">
                    <QueryImage
                      imageKey={product.imageKeys[0] ?? undefined}
                      defaultImage={DefaultImage}
                      wrapperClassName="rounded-lg w-32 h-16 shrink-0"
                      imgClassName="rounded-lg w-full h-full object-cover"
                    />
                    <span>x {count}</span>
                  </div>
                  <div className="space-y-1">
                    <div>{product.name}</div>
                    <div className="text-end">
                      ￥{count * Number(product.price)}
                    </div>
                  </div>
                </div>
              );
            })
          )}
        </div>
        {!productsError && (
          <div className="text-xl font-bold">
            总价：
            {Math.round(
              orderData.products.reduce((total, { id, count }) => {
                const product = productsData.find((p) => p.id === id);
                if (!product) return total;
                return total + count * Number(product.price);
              }, 0) * 100,
            ) / 100}
            元
          </div>
        )}
        <div className="space-y-4">
          <div className="font-bold text-lg">订单信息</div>
          {[
            {
              label: '订单号：',
              value: orderData.id,
            },
            {
              label: '收货地址：',
              value: orderData.address,
            },
            {
              label: '联系人：',
              value: orderData.userName,
            },
            {
              label: '联系电话：',
              value: orderData.userPhone,
            },
            {
              label: '下单时间：',
              value: dayjs(orderData.createdAt).format('YYYY-MM-DD HH:mm:ss'),
            },
            {
              label: '备注：',
              value: orderData.remark ?? '无',
            },
          ].map(({ label, value }) => (
            <div key={label} className="flex items-center">
              <div className="w-0 text-nowrap">{label}</div>
              <div className="text-sm ml-32">{value}</div>
            </div>
          ))}
        </div>
        {orderData.status === 'completed' && (
          <div className="space-y-3">
            <div className="font-bold text-lg">订单评价</div>
            <div className="flex items-center gap-2">
              配送评分：
              {rateArray.map((rate) => (
                <span
                  key={rate}
                  className={cn(
                    'text-xl',
                    rate < orderData.evaluation.deliver
                      ? 'i-ri-star-fill'
                      : 'i-ri-star-line',
                  )}
                />
              ))}
            </div>
            <div className="flex items-center gap-2">
              产品评分：
              {rateArray.map((rate) => (
                <span
                  key={rate}
                  className={cn(
                    'text-xl',
                    rate < orderData.evaluation.product
                      ? 'i-ri-star-fill'
                      : 'i-ri-star-line',
                  )}
                />
              ))}
            </div>
          </div>
        )}
      </div>
    </LeftToRightView>
  );
}
